//
//  CMRootViewController.m
//  CloudMonitoring
//
//  Created by TerryChe on 2016/12/20.
//  Copyright © 2016年 TerryChe. All rights reserved.
//
#import "CMDetailViewController.h"
#import "CMConfigViewController.h"
#import "SKPSMTPMessage.h"
#import "NSData+Base64Additions.h"

#import "PrefixHeader.pch"

#import <CommonCrypto/CommonDigest.h>

@interface CMDetailViewController()<SKPSMTPMessageDelegate, UITableViewDataSource, UITableViewDelegate>

    @property (weak, nonatomic) IBOutlet UITableView *tableView;
    @property (weak, nonatomic) IBOutlet UITextView *TextView;
    
    - (IBAction)btnUploadClick:(id)sender;
    
    @property (nonatomic, strong) NSMutableArray<NSString *> *nameArr;

    @property (nonatomic, strong) NSString *apiUrl;
    @property (nonatomic, strong) NSString *token;

@end

@implementation CMDetailViewController

- (void)loadView {
	[super loadView];

	self.title = @"正在监控的微信";
    
    self.tableView.allowsSelection = NO;
    
    [self loadDir];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"刷新" style:UIBarButtonItemStylePlain target:self action:@selector(loadDir)];
    
	self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"配置" style:UIBarButtonItemStylePlain target:self action:@selector(config)];
}

-(void)loadDir{
    //加载config文件
    NSString *path = [str_cm_dir stringByAppendingPathComponent:str_cm_config];
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
    
    if (dic == nil || dic.count == 0) {
        return;
    }
    
    self.apiUrl = dic[@"address"];
    NSString *appid = dic[@"appID"];
    NSString *appKey = dic[@"appKey"];
    NSString *nonce = dic[@"nonce"];
    self.token = dic[@"token"];
    UInt64 expiresIn = 0;
    if (dic[@"expiresIn"] != nil) {
        expiresIn = [dic[@"expiresIn"] unsignedLongLongValue];
    }
    
    UInt64 nowInterval = [[NSDate date] timeIntervalSince1970];
    if (expiresIn == 0 || expiresIn < nowInterval ||
        self.token == nil || [self.token isEqualToString:@""])
    {
        NSMutableDictionary *dicParams = [[NSMutableDictionary alloc]init];
        [dicParams setObject:appid forKey:@"appId"];
        [dicParams setObject:[NSString stringWithFormat:@"%llu", nowInterval] forKey:@"timestamp"];
        [dicParams setObject:nonce forKey:@"nonce"];
        NSString* str = [NSString stringWithFormat:@"%@%llu%@", appKey, nowInterval, nonce];
        [dicParams setObject:[self sha1:str] forKey:@"signature"];
        
        NSString* url = [NSString stringWithFormat:@"%@/api/LoginToken?format=json", self.apiUrl];
        OPHRequest *request = [OPHRequest jsonReqeust:url type:OPH_HTTP_POST params:dicParams];
        OPHResponse *response = [[OPHNetwork sharedInstance] syncRequest:request];
        
        if ([response isRequestOk]) {
            OPHJsonStatusResult* jsonResult = [response expectedJsonStatusResultObject];
            
            if ([jsonResult isResultSuccess]) {
                self.token = jsonResult.result[@"access_token"];
                expiresIn = [jsonResult.result[@"expires_in"] unsignedLongLongValue];
                
                [dic setObject:self.token forKey:@"token"];
                [dic setObject:@(expiresIn) forKey:@"expiresIn"];
                NSString *configPath = [str_cm_dir stringByAppendingPathComponent:str_cm_config];
                [dic writeToFile:configPath atomically:YES];
            }
        }
    }
    
    //加载微信帐号
    self.nameArr = [[NSMutableArray alloc] init];
    
    NSString *userPath = [str_cm_dir stringByAppendingPathComponent:str_cm_user];
    NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:userPath];
    for (NSString *name in data.allValues) {
        [self.nameArr addObject:name];
    }
    
    if(self.nameArr.count == 0){
//        [self alertView:@"没有检测到微信帐号，请稍后刷新"];
        [SVProgressHUD showInfoWithStatus:@"没有检测到微信帐号，请稍后刷新"];
    }
    
    [self.tableView reloadData];
    
    [self.TextView setEditable:NO];
    
    NSString *logPath = [str_cm_dir stringByAppendingPathComponent:str_cm_log];
    if ([[NSFileManager defaultManager] fileExistsAtPath:logPath]) {
        @try {
            NSString *str = [[NSString alloc] initWithContentsOfFile:logPath encoding:NSUTF8StringEncoding error:nil];
            self.TextView.text = str;
        }
        @catch (NSException *exception) {
            NSLog(@"捕捉到错误 %@ ：%@", exception.name ,exception.reason);
        }
    }
}

- (void)config {
    UIViewController *vc = [[UIStoryboard storyboardWithName:@"CMConfig" bundle:nil] instantiateInitialViewController];

    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - Table View Data Source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return self.nameArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *CellIdentifier = @"Cell";
	__block UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

	if (!cell) {
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
	}

	NSString *name = self.nameArr[indexPath.row];
	cell.textLabel.text = name;
    
    if([self.token isEqualToString:@""]){
        cell.detailTextLabel.text = @"网络连接失败";
        cell.detailTextLabel.textColor = [UIColor colorWithRed:(255/255.0) green:(95/255.0) blue:(62/255.0) alpha:1];
    }else{
        cell.detailTextLabel.text = @"正在查询状态";
    }
    
    NSString* url = [NSString stringWithFormat:@"%@/api/weichart?format=json&access_token=%@&wenober=%@", self.apiUrl, self.token, name];
    OPHRequest* request = [OPHRequest jsonReqeust:url type:OPH_HTTP_GET];
    [[OPHNetwork sharedInstance] asyncRequest:request resultBlock:^(OPHResponse* response){
        NSString *str = @"网络连接失败";
        UIColor *color = [UIColor colorWithRed:(255/255.0) green:(95/255.0) blue:(62/255.0) alpha:1];
        
        if ([response isRequestOk]) {
            str = @"没有监控授权";
            color = [UIColor colorWithRed:(192/255.0) green:(200/255.0) blue:(200/255.0) alpha:1];
            
            OPHJsonStatusResult* jsonResult = [response expectedJsonStatusResultObject];
    
            if ([jsonResult isResultSuccess]) {
                BOOL friends = [jsonResult.result[@"ad_wechat_friends"] boolValue];
                BOOL chat = [jsonResult.result[@"ad_wechat_chat"] boolValue];
                
                if(chat){
                    str = @"好友+聊天监控";
                    color = [UIColor colorWithRed:(106/255.0) green:(194/255.0) blue:(11/255.0) alpha:1];
                }
                else if(friends){
                    str = @"好友监控";
                    color = [UIColor colorWithRed:(77/255.0) green:(166/255.0) blue:(240/255.0) alpha:1];
                }
            }
        }
        
        dispatch_sync(dispatch_get_main_queue(),^{
            cell.detailTextLabel.text = str;
            cell.detailTextLabel.textColor = color;
        });
    }];
    
	return cell;
}

//sha1加密方式
- (NSString *) sha1:(NSString *)input {
    NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding];
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1(data.bytes, (unsigned int)data.length, digest);
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i=0; i<CC_SHA1_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }
    
    return output;
}

- (IBAction)btnUploadClick:(id)sender {
    [SVProgressHUD showWithStatus:@"正在上传，请稍后！"];
    //        设置基本参数：
    SKPSMTPMessage *mail = [[SKPSMTPMessage alloc] init];
    [mail setSubject:@"iOS WeChatTool log"];  // 设置邮件主题
    [mail setToEmail:@"84436941@qq.com"]; // 目标邮箱
    [mail setFromEmail:@"chezz@agsoft.net"]; // 发送者邮箱
    [mail setRelayHost:@"smtp.exmail.qq.com"]; // 发送邮件代理服务器
    
    [mail setRequiresAuth:YES];
    [mail setLogin:@"chezz@agsoft.net"]; // 发送者邮箱账号
    [mail setPass:@"m6t-NwD-Tky-7ZU"]; // 发送者邮箱密码
    [mail setWantsSecure:YES];  // 需要加密
    [mail setDelegate:self];
    
    NSMutableArray *arrParts = [[NSMutableArray alloc] init];
    //        设置邮件正文内容：
    NSDictionary *plainPart = @{kSKPSMTPPartContentTypeKey : @"text/plain;charset=UTF-8",
                                kSKPSMTPPartMessageKey : [NSString stringWithCString:"查看附件" encoding:NSUTF8StringEncoding],
                                kSKPSMTPPartContentTransferEncodingKey : @"8bit"};
    [arrParts addObject:plainPart];
    
    //        添加附件（以下代码可在SKPSMTPMessage库的DMEO里找到）：
    NSString *fileBase64 = @"";
    NSString *vcfPath = [str_cm_dir stringByAppendingPathComponent:str_cm_logList];
    if ([[NSFileManager defaultManager] fileExistsAtPath:vcfPath]) {
        NSData *vcfData = [NSData dataWithContentsOfFile:vcfPath];
        fileBase64 = [vcfData encodeBase64ForData];
    }
    else {
        NSData *data = [_TextView.text dataUsingEncoding:NSUTF8StringEncoding];
        fileBase64 = [data encodeBase64ForData];
    }

    NSDictionary *vcfPart = [NSDictionary dictionaryWithObjectsAndKeys:@"text/directory;x-unix-mode=0644;name=\"log.plist\"",kSKPSMTPPartContentTypeKey,@"attachment;filename=\"log.plist\"",kSKPSMTPPartContentDispositionKey,fileBase64,kSKPSMTPPartMessageKey,@"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
    [arrParts addObject:vcfPart];

    //LocalInfo
    NSString *localInfoPath = [[str_cm_dir stringByAppendingPathComponent:_nameArr.firstObject] stringByAppendingPathComponent:str_cm_localInfo];
    if ([[NSFileManager defaultManager] fileExistsAtPath:localInfoPath]) {
        NSData *data = [NSData dataWithContentsOfFile:localInfoPath];
        NSString *fileBase64 = [data encodeBase64ForData];
        NSDictionary *part = [NSDictionary dictionaryWithObjectsAndKeys:@"text/directory;x-unix-mode=0644;name=\"localInfo.plist\"",kSKPSMTPPartContentTypeKey,@"attachment;filename=\"localInfo.plist\"",kSKPSMTPPartContentDispositionKey,fileBase64,kSKPSMTPPartMessageKey,@"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
        [arrParts addObject:part];
    }

    //mmsetting
    NSString *mmsettingPath = [[str_cm_dir stringByAppendingPathComponent:_nameArr.firstObject] stringByAppendingPathComponent:str_cm_mmsetting];
    if ([[NSFileManager defaultManager] fileExistsAtPath:mmsettingPath]) {
        NSData *data = [NSData dataWithContentsOfFile:mmsettingPath];
        NSString *fileBase64 = [data encodeBase64ForData];
        NSDictionary *part = [NSDictionary dictionaryWithObjectsAndKeys:@"text/directory;x-unix-mode=0644;name=\"mmsetting.plist\"",kSKPSMTPPartContentTypeKey,@"attachment;filename=\"mmsetting.plist\"",kSKPSMTPPartContentDispositionKey,fileBase64,kSKPSMTPPartMessageKey,@"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
        [arrParts addObject:part];
    }

    [mail setParts:arrParts]; // 邮件首部字段、邮件内容格式和传输编码
    //        执行发送邮件代码：
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [mail send];
//    });
}
    
//- (void)alertView:(NSString *)text
//{
//    if(iosVerion < 8.0) {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:text delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
//        [alert show];
//    } else {
//        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:text preferredStyle:UIAlertControllerStyleAlert];
//
//        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil];
//        [alertController addAction:okAction];
//
//        [self presentViewController:alertController animated:YES completion:nil];
//    }
//}

- (void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error {
//    [self alertView:@"上传失败，请重新上传！"];
    [SVProgressHUD showErrorWithStatus:@"上传失败，请重新上传！"];
}

- (void)messageSent:(SKPSMTPMessage *)message {
//    [self alertView:@"上传成功！"];
    [SVProgressHUD showSuccessWithStatus:@"上传成功！"];
}

@end
